package java8.myStream;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * 功能描述:标测采集试验
 * 2024/08/26
 *
 * @author ZhangYi
 */
public class MappingCollectiorTest {
	public static void main(String[] args) {
		List<Person> people = Arrays.asList(
				new Person("Alice", 20),
				new Person("Bob", 17),
				new Person("Charlie", 22),
				new Person("Diana", 19),
				new Person("Eve", 25),
				new Person("Frank", 16)
		);

		// 1. 提取所有人的名字
		List<String> names = people.stream()
				.collect(Collectors.mapping(Person::getName, Collectors.toList()));
		System.out.println("Names: " + names);

		// 2. 计算所有人的年龄之和
		int totalAge = people.stream()
				.collect(Collectors.mapping(Person::getAge, Collectors.summingInt(Integer::intValue)));
		System.out.println("Total Age: " + totalAge);

		// 3. 计算所有人的年龄平均值
		double averageAge = people.stream()
				.collect(Collectors.mapping(Person::getAge, Collectors.averagingInt(Integer::intValue)));
		System.out.println("Average Age: " + averageAge);

		// 4. 统计不同年龄的人数
		Map<Integer, Long> ageCount = people.stream()
				.collect(Collectors.mapping(Person::getAge, Collectors.groupingBy(
						Function.identity(), Collectors.counting())));
		System.out.println("Age Count: " + ageCount);

		// 5. 统计不同名字的出现次数,
		Map<String, Long> nameCount = people.stream()
				.collect(Collectors.mapping(Person::getName, Collectors.groupingBy(
						Function.identity(), Collectors.counting())));
		System.out.println("Name Count: " + nameCount);

		// 6. 将所有人按照年龄分组
		Map<Integer, List<Person>> groupedByAge = people.stream()
				.collect(Collectors.groupingBy(Person::getAge,
						Collectors.mapping(Function.identity(), Collectors.toList())));
		System.out.println("Grouped by Age: " + groupedByAge);
	}
}
